import json

import pymongo
from flask import Blueprint
from flask import redirect,views
from flask import request,jsonify

from Socket_msg_view import socketio
from tools import MyMongo,MyRedis
customer_ser = Blueprint("customer_ser", __name__)

@customer_ser.route('/customer_ser/',methods=['GET','POST'])
def get_sid():
    with MyMongo(db='md',table='socket_message') as c:
        channels = list(c.find({},{'_id':0}))[::-1]
    return jsonify({'code':200,'channels':channels})


@customer_ser.route('/get_channel_info/',methods=['GET','POST'])
def get_channel_info():
    sid =request.args.get('sid').strip()
    username = request.args.get('username').strip()
    with MyMongo(db='md',table='socket_message') as c:
        # data = list(c.find({'sid':sid},{'_id':0}))
        c.update_one({'sid': sid}, {'$set': {'is_reply':1,'replyer':username}})
    return jsonify({'code':200,'msg':'ok'})

@customer_ser.route('/get_messages_push/',methods=['GET','POST'])
def get_messages_push():
    province= request.args.get('province')
    model= request.args.get('model')
    res_list=[]
    with MyMongo(db='md', table='message_box') as c:
        message_list = list(c.find({},{'_id':0}).sort('sendtime',pymongo.DESCENDING))
    for msg in message_list:
        # 如果机型在之内
        if model in msg['machine_type']:
            # 如果存在 指定城市
            if msg['place']:
                if  province in msg['place']: # 如果城市符合
                    # 将符合的数据添加进返回list中
                    res_list.append(msg)
            else:
                # 将符合的数据添加进返回list中
                res_list.append(msg)
    return jsonify({'code':200,'data':res_list})




import  arrow
@customer_ser.route('/cont_check/',methods=['GET','POST'])
def cont_check():
    check_list=request.args.get('check_list')
    if check_list:
        dict= eval(check_list)
        n = arrow.now()
        with MyRedis()as r:
            for k,v in dict.items():
                # 如果当前title存在
                if r.hget(n.format('YYYY-MM-DD'),k):
                    r.hincrby(n.format('YYYY-MM-DD'),k,+v) # 累计增加
                else:
                    r.hset(n.format('YYYY-MM-DD'), k, v)
    return jsonify({'code':200,})


@customer_ser.route('/get_check_num/',methods=['GET','POST'])
def get_check_num():
    with MyMongo(db='md', table='check_count') as c:
        res=list(c.find({},{'_id':0}).sort('time',pymongo.DESCENDING))
    return jsonify({'code': 200,'data':res})


@customer_ser.route('/get_places/',methods=['GET','POST'])
def get_places():

    with MyMongo(db='md', table='places')as c:
        res= list(c.find({},{'_id':0}))
    return jsonify({'code': 200,'data':res})

